package com.pw.study.flink.watermark;

import com.pw.study.flink.entities.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

public class WaterMarkFunction {
    public static void main(String[] args) {
        wc1();
    }

    private static void wc1() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
//1.数据构建
        SingleOutputStreamOperator<WaterSensor> stream = env.socketTextStream("hadoop111", 9999).map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] data = value.split(" ");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            }
        });
//2.方法构建
       // fun(stream);
        fun2(stream);


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void fun2(SingleOutputStreamOperator<WaterSensor> stream) {
        stream.keyBy(WaterSensor::getId).process(new KeyedProcessFunction<String, WaterSensor, String>() {
            @Override
            public void processElement(WaterSensor sensor, Context ctx, Collector<String> out) throws Exception {
                System.out.println("ctx "+ctx.getCurrentKey()+" sensor "+ ctx.toString());
                out.collect("sensor..."+sensor);
            }
        }).print();
    }

    private static void fun(SingleOutputStreamOperator<WaterSensor> stream) {
        stream.process(new ProcessFunction<WaterSensor, String>() {
            @Override
            public void processElement(WaterSensor sensor, Context ctx, Collector<String> out) throws Exception {
                System.out.println("ctx.."+ctx.toString());
                out.collect("value: "+sensor+"... ");
            }
        }).print();
    }
}
